import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter_ahj_app/TestViewModel.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetFilesPath.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetImageWidget.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class ShowImage extends BaseStatefulWidget {
  Map imageInfo; // position filePath

  ShowImage({this.imageInfo});

  @override
  State<StatefulWidget> initState() {
    // TODO: implement createState
    return ShowImageState();
  }
}

class ShowImageState extends BaseState<TestViewModel,ShowImage> {
  PageController pageController;

  @override
  void initState() {
    super.initState();
    pageController = new PageController(initialPage: widget.imageInfo['position']);
  }

  @override
  Widget initWidget() {
    // TODO: implement initWidget
    return Scaffold(
      appBar: MTopBar(
        title: (widget.imageInfo['position'] + 1).toString() + "/" + widget.imageInfo['filePath'].length.toString(),
      ).create(),
      body: _bodyView(),
    );
  }

  Widget _bodyView() {
    return PageView(
      children: _getItems(),
      controller: pageController,
      onPageChanged: (int index) => _change(index),
    );
  }

  List<Widget> _getItems() {
    // 不带分割线的item...
    List<Widget> items = new List();
    for (int i = 0; i < widget.imageInfo['filePath'].length; i++) {
      items.add(
        GestureDetector(

          onLongPress: () => _longPressEvent(widget.imageInfo['filePath'][i]),
                  child: Container(
            color: Colors.black,
            child: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: ImageWidget(
                fileName: widget.imageInfo['filePath'][i],
                width: ScreenUtil.getScreenW(context),
                height: ScreenUtil.getScreenH(context),
              ),
            ),
          ),
        ),
      );
    }
    return items;
  }

  // 当整个页面 dispose 时，记得把控制器也 dispose 掉，释放内存
  @override
  void dispose() {
    this.pageController.dispose();
    super.dispose();
  }

  _change(int index) {
    if (widget.imageInfo['position'] == index) return;
    setState(() {
      widget.imageInfo['position'] = index;
    });
  }

  /// 长按 保存 图片
  _longPressEvent(String filesName) async {
    bool isSave = await _showDeleteConfirmDialog();
    if (isSave == true) {
      print('保存图片');
      if (Platform.isIOS) {
        FilesPath.getFilePath(filesName, (url) {
          _saveNetImage(url);
        });
      } else {
        FilesPath.getFilePath(filesName, (url) {
          _saveNetImage(url);
        });
      }
    }
  }

  // 弹出对话框
  Future<bool> _showDeleteConfirmDialog() {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("您确定要保存当前图片吗?"),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
            ),
            FlatButton(
              child: Text("确定"),
              onPressed: () {
                //关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }

  ///保存 图片
  _saveNetImage(String url) async {
    ///判断 权限
    String resultStr =
        await PerUtils.checkPermission(context, [Permission.photos,Permission.storage]);

    if (resultStr == '0') {
      ToastUtils.showToast("您没有开启保存图片的权限，不能进行保存");
      return;
    } else if (resultStr == '1') {
      var response = await Dio()
          .get(url, options: Options(responseType: ResponseType.bytes));
      final result =
          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      print(result);

      if (Platform.isIOS) {
        if (result) {
          ToastUtils.showToast('保存成功');
        } else {
          ToastUtils.showToast('保存失败');
        }
      } else {
        if (result != null) {
          ToastUtils.showToast('保存成功');
        } else {
          ToastUtils.showToast('保存失败');
        }
      }
    }
  }
}
